package pkt

import (
	"encoding/binary"
)

const (
	NET_KEEPALIVE         = 1
	NET_HELLO             = 2
	NET_DEV_SERVER_NOTIFY = 3 //通知设备来连接
)

type CmdPkt struct {
	Cmd  uint32
	Data []byte
}

func (v *CmdPkt) PackLen() int {
	return 4 + len(v.Data)
}

func (v *CmdPkt) Pack() []byte {
	//还有个长度
	buf := make([]byte, v.PackLen()+4)
	index := 0
	binary.BigEndian.PutUint32(buf[index:], v.Cmd)
	index += 4
	binary.BigEndian.PutUint32(buf[index:], uint32(len(v.Data)))
	index += 4
	copy(buf[index:], v.Data[0:])

	return buf
}

func (v *CmdPkt) SendPack() []byte {
	buf := v.Pack()
	sbuf := make([]byte, len(buf)+4)
	binary.BigEndian.PutUint32(sbuf, uint32(len(buf)))
	copy(sbuf[4:], buf)

	return sbuf
}

func (v *CmdPkt) UnPack(buf []byte) int {
	if len(buf) < 8 {
		return -1
	}
	index := 0
	v.Cmd = binary.BigEndian.Uint32(buf[index:])
	index += 4
	len := binary.BigEndian.Uint32(buf[index:])
	index += 4
	v.Data = make([]byte, len)
	copy(v.Data[0:], buf[index:])

	return v.PackLen()
}
